import socket as sk
import datetime
    
def rcv(s):
    '''receive all there is to receive from socket s'''
    st=''
    t=''
    while True:
        t = s.recv(4096)
        if len(t)==0:
            break
        st=st+t
    s.close()
    return st

def send(st,a,p):
    '''send string st to address a and port p'''
    s = sk.socket(sk.AF_INET, sk.SOCK_STREAM)
    s.setblocking(True)
    s.connect((a,p))
    s.sendall(st)
    s.close()

def stime():
    '''get date-time string'''
    return str(datetime.datetime.now())


def serve(a,p,mws,fnc0, fnc1=None,hello=None):
    '''blocking function.
    listen at address a, at port p,
    pass incoming strings to function fnc0
    and call optional function fnc1 when idle.
    (at most 100 times a second)
    if received string == mws
    then server exits.
    mws is the magic word to stop the server.
    hello is the greeting printed when server is up.'''
    s = sk.socket(sk.AF_INET, sk.SOCK_STREAM)
    s.settimeout(0.01) # call fnc1 at most 100 times a sec
    s.bind((a,p))
    s.listen(13)
    print stime()+' server is listening at address '+a+':'+str(p)
    if hello!=None:
        print hello
    while True:
        cs=None
        try:
            (cs, addr) = s.accept()
        except sk.timeout:
            if fnc1!=None:
                fnc1()
        if cs==None:
            continue
        cs.setblocking(True)
        st=rcv(cs)
        print st
        if st==mws:
            if cs!=None:
                cs.close()
            s.close()
            break
        fnc0(st)






